package com.java.miaosha.controller;

import com.java.miaosha.constants.Constants;
import com.java.miaosha.entity.UserEntity;
import com.java.miaosha.exception.GlobalException;
import com.java.miaosha.service.GoodsService;
import com.java.miaosha.service.UserService;
import com.java.miaosha.vo.GoodsVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author jiangli
 * @date 2019/8/31 12:35
 */
@Controller
@RequestMapping("/goods")
public class GoodsController {
	@Autowired
	private UserService userService;
	@Autowired
	private GoodsService goodsService;

	@GetMapping("/to_list")
	public String toList(Model model, @CookieValue(value = Constants.TOKEN,required = false)String cookieToken,
						 @RequestParam(value = Constants.TOKEN,required = false)String paramToken) {
		if (StringUtils.isEmpty(cookieToken)&&StringUtils.isEmpty(paramToken)){
			//token都为空跳转到登录页
			return "login";
		}
		String token = StringUtils.isNotEmpty(cookieToken)?cookieToken:paramToken;
		UserEntity user = userService.getUserByToken(token);
		model.addAttribute("user",user);
		List<GoodsVO> goodsList = goodsService.goodsVOList();
		model.addAttribute("goodsList",goodsList);
		return "goods_list";
	}

	@GetMapping("/to_detail/{goodsId}")
	public String toDetail(Model model, @PathVariable("goodsId") Long goodsId) {
		GoodsVO goodsVO = goodsService.getGoodsVOById(goodsId);
		if (goodsVO == null) {
			throw new GlobalException(Constants.GOODS_NOT_EXISTS);
		}
		long startAt = goodsVO.getStartDate().getTime();
		long endAt = goodsVO.getEndDate().getTime();
		long  now = new Date().getTime();

		int miaoshaStatus = 0;
		int remainSeconds = 0;
		if (now < startAt) { //秒杀未开始
			miaoshaStatus = 0;
			remainSeconds = (int) ((startAt-now)/1000);
		} else if (now > endAt) { //秒杀已结束
			miaoshaStatus = -1;
			remainSeconds = -1;
		} else { //秒杀进行中
			miaoshaStatus = 1;
			remainSeconds = 0;
		}
		model.addAttribute("goods",goodsVO);
		model.addAttribute("miaoshaStatus",miaoshaStatus);
		model.addAttribute("remainSeconds",remainSeconds);
		return "goods_detail";
	}

	@GetMapping("/jmeter")
	@ResponseBody
	public String jmeter() {
		System.out.println("test");
		return null;
	}
}
